﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Diagnostics;
using Hammock;
using Hammock.Authentication.OAuth;
using System.Text.RegularExpressions;
using Hammock.Silverlight.Compat;
using System.Threading;
using Hammock.Tasks;

namespace Tweet_for_Windows_Phone_7_Series
{
    public partial class PageAuthorize : PhoneApplicationPage
    {
        public string authURL { get; set; }

        public PageAuthorize()
        {
            InitializeComponent();
        }

        private string authority = @"https://api.twitter.com/oauth/";
        private const string ConsumerKey = "AeKD608GePKuIbyMLlQtA";
        private const string ConsumerSecret = "IXErMFzH4UJzlFe3nwJmWiCELSmbbYwLv05xACV5hxk";
        private string url;

        private string responsestring = string.Empty;

        public void getRequestToken()
        {
            RestClient c = new RestClient()
            {
                Authority = authority,
                HasElevatedPermissions = true,
                Credentials = new OAuthCredentials()
                {
                    Type = OAuthType.RequestToken,
                    ConsumerKey = ConsumerKey,
                    ConsumerSecret = ConsumerSecret,
                    SignatureMethod = OAuthSignatureMethod.HmacSha1,
                    ParameterHandling = OAuthParameterHandling.HttpAuthorizationHeader,
                }
            };

            RestRequest r = new RestRequest()
            {
                Path = "request_token",
            };

            RestCallback cb = new RestCallback(Callback);
            c.BeginRequest(r, cb);
        }

        NameValueCollection token = new NameValueCollection();

        private void Callback(Hammock.RestRequest request, Hammock.RestResponse response, object userState)
        {
            var a = response.Content;
            Debug.WriteLine(a);

            Regex r = new Regex("oauth_token=([^&.]*)&oauth_token_secret=([^&.]*)");

            Match match = r.Match(a);
            try
            {
                if (match.Success)
                {
                    foreach (string s in match.Value.Split('&'))
                    {
                        token.Add(s.Split('=')[0], s.Split('=')[1]);
                    }

                    url = String.Format("{0}{1}?oauth_token={2}", authority, "authorize", token["oauth_token"]);
                    Debug.WriteLine(url);
                    Dispatcher.BeginInvoke(() => { browserAuthorize.Navigate(new Uri(url)); });
                    
                }
                else
                    throw new WebException("not authorized", WebExceptionStatus.TrustFailure);
            }
            catch (Exception ex)
            {

            }


        }     

        private void pAuthorize_Loaded(object sender, RoutedEventArgs e)
        {
            getRequestToken();
            browserAuthorize.Navigating += new EventHandler<NavigatingEventArgs>(browserAuthorize_Navigating);

        }

        void browserAuthorize_Navigating(object sender, NavigatingEventArgs e)
        {
            Debug.WriteLine(string.Format("Navigating to: {0}",e.Uri));
            if (e.Uri.ToString().StartsWith("http://tweet-callback.com"))
            {
                Debug.WriteLine("Callback fired");
                this.ContentPanel.Children.Remove(browserAuthorize);
                this.ContentPanel.UpdateLayout();
            }
        }
    }
}